#!/usr/bin/env bash
set -euo pipefail

BUNDLE_MACOS_DIR="$(cd "$(dirname "$0")" && pwd)"
BUNDLE_RES_DIR="$(cd "$BUNDLE_MACOS_DIR/../Resources" && pwd)"
APP_ROOT="$HOME/Library/Application Support/Termin-Kalender-Desktop"
APP_DIR="$APP_ROOT/app"
RUNTIME_DIR="$APP_ROOT/runtime"
DATA_DIR="$APP_ROOT/data"
PORT=13585
APP_URL="http://127.0.0.1:${PORT}"

mkdir -p "$APP_DIR" "$RUNTIME_DIR" "$DATA_DIR"

# 1. App-Code beim ersten Start nach Application Support entpacken (1-Klick-Updates bleiben beschreibbar)
if [ ! -f "$APP_DIR/server.mjs" ] && [ -f "$BUNDLE_RES_DIR/app.zip" ]; then
    /usr/bin/unzip -oq "$BUNDLE_RES_DIR/app.zip" -d "$APP_DIR"
fi

# 2. Desktop-Verknüpfung (Alias) beim ersten Start anbieten/anlegen
DESKTOP_LINK="$HOME/Desktop/Termin-Kalender PRO Desktop.app"
THIS_APP_BUNDLE="$(cd "$BUNDLE_MACOS_DIR/../.." && pwd)"
if [ ! -e "$DESKTOP_LINK" ] && [ -d "$THIS_APP_BUNDLE" ]; then
    ln -s "$THIS_APP_BUNDLE" "$DESKTOP_LINK" 2>/dev/null || true
fi

# 3. Node.js >= 18 ermitteln oder einmalig portabel nach runtime/ laden (Apple Silicon & Intel)
check_node_major() {
    local bin="$1"
    [ -x "$bin" ] || return 1
    local maj
    maj="$("$bin" -p "parseInt(process.versions.node.split('.')[0], 10)" 2>/dev/null || echo 0)"
    [ "$maj" -ge 18 ]
}

NODE_BIN=""
for cand in "$RUNTIME_DIR/bin/node" "$(command -v node || true)" "/opt/homebrew/bin/node" "/usr/local/bin/node"; do
    if [ -n "$cand" ] && check_node_major "$cand"; then
        NODE_BIN="$cand"
        break
    fi
done

if [ -z "$NODE_BIN" ]; then
    ARCH="$(uname -m)"
    if [ "$ARCH" = "arm64" ]; then NODE_ARCH="darwin-arm64"; else NODE_ARCH="darwin-x64"; fi
    /usr/bin/osascript -e 'display notification "Lade kompakte Laufzeitumgebung (einmalig)..." with title "Termin-Kalender Desktop"' || true
    TARBALL_NAME="$(/usr/bin/curl -fsSL "https://nodejs.org/dist/latest-v22.x/SHASUMS256.txt" | grep -E "node-v22\.[0-9.]+-${NODE_ARCH}\.tar\.gz$" | head -n1 | awk '{print $2}')"
    if [ -n "$TARBALL_NAME" ]; then
        TMP_TGZ="$APP_ROOT/node-runtime.tar.gz"
        /usr/bin/curl -fsSL "https://nodejs.org/dist/latest-v22.x/${TARBALL_NAME}" -o "$TMP_TGZ"
        rm -rf "$RUNTIME_DIR" && mkdir -p "$RUNTIME_DIR"
        /usr/bin/tar -xzf "$TMP_TGZ" -C "$RUNTIME_DIR" --strip-components=1
        rm -f "$TMP_TGZ"
        NODE_BIN="$RUNTIME_DIR/bin/node"
    fi
fi

if [ -z "$NODE_BIN" ] || [ ! -x "$NODE_BIN" ]; then
    /usr/bin/osascript -e 'display alert "Termin-Kalender Desktop" message "Node.js konnte nicht eingerichtet werden. Bitte prüfen Sie Ihre Internetverbindung." as critical' || true
    exit 1
fi

# 4. Lokalen Server starten falls Port noch nicht belegt
if ! /usr/bin/nc -z 127.0.0.1 "$PORT" >/dev/null 2>&1; then
    TK_DATA_DIR="$DATA_DIR" PORT="$PORT" nohup "$NODE_BIN" "$APP_DIR/server.mjs" >/dev/null 2>&1 &
    for _ in $(seq 1 40); do
        if /usr/bin/nc -z 127.0.0.1 "$PORT" >/dev/null 2>&1; then break; fi
        sleep 0.2
    done
fi

# 5. Als eigenständiges App-Fenster öffnen
if [ -d "/Applications/Google Chrome.app" ]; then
    open -na "Google Chrome" --args --app="$APP_URL" --window-size=1540,940
elif [ -d "/Applications/Microsoft Edge.app" ]; then
    open -na "Microsoft Edge" --args --app="$APP_URL" --window-size=1540,940
elif [ -d "/Applications/Brave Browser.app" ]; then
    open -na "Brave Browser" --args --app="$APP_URL" --window-size=1540,940
else
    open "$APP_URL"
fi
